#include "stdafx.h"
#include "JGraphRowColGenerator.h"
#include "JGraph.h"
#include "JPoint.h"
#include "JPiece.h"
#include "JBoundary.h"
#include "JGraphOrigin.h"

int JGraphRowColGenerator::m_nRowNum = 3;
int JGraphRowColGenerator::m_nColNum = 3;

JGraphRowColGenerator::JGraphRowColGenerator()
	
{
}


JGraphRowColGenerator::~JGraphRowColGenerator()
{
}

void JGraphRowColGenerator::SetRowNum(int _row)
{
	m_nRowNum = _row;
}

void JGraphRowColGenerator::SetColNum(int _col)
{
	m_nColNum = _col;
}

int JGraphRowColGenerator::GetRowNum()
{
	return m_nRowNum;
}

int JGraphRowColGenerator::GetColNum()
{
	return m_nColNum;
}

JGraphOrigin* JGraphRowColGenerator::CreateGraph(RECT _rc)
{

	int width = _rc.right - _rc.left;
	int height = _rc.bottom - _rc.top;

	int iw = width / m_nColNum;
	int ih = height / m_nRowNum;
	if (iw == 0 || 
		ih == 0)
	{
		return 0;
	}

	JGraphOrigin* pGraph = new JGraphOrigin;
	//Generate Points
	int i, j;
	for (i = 0; i <= m_nRowNum; ++i)
	{
		for (j = 0; j <= m_nColNum; ++j)
		{
			pGraph->AddPoint(new JPoint(_rc.left + iw * j, _rc.top + ih * i));
		}
	}

	//Generate Boundaries
	for (i = 0; i <= m_nRowNum; ++i)
	{
		for (j = 0; j < m_nColNum; ++j)
		{
			pGraph->AddBoundary(
				new JBoundary(pGraph->GetPoint(i * (m_nColNum + 1) + j),
				pGraph->GetPoint(i * (m_nColNum + 1) + j + 1)));
		}
	}
	for (i = 0; i < m_nRowNum; ++i)
	{
		for (j = 0; j <= m_nColNum; ++j)
		{
			pGraph->AddBoundary(
				new JBoundary(pGraph->GetPoint(i * (m_nColNum + 1) + j),
				pGraph->GetPoint((i + 1) * (m_nColNum + 1) + j)));
		}
	}
	

	//Generate Pieces
	JPiece* pPiece;
	for (i = 0; i < m_nRowNum; ++i)
	{
		for (j = 0; j < m_nColNum; ++j)
		{
			pPiece = new JPiece;
			pPiece->AddBoundary(pGraph->GetBoundary(i*(m_nColNum + 1) + j, 
				i*(m_nColNum + 1) + j + 1));
			pPiece->AddBoundary(pGraph->GetBoundary(i*(m_nColNum + 1) + j + 1,
				(i + 1)*(m_nColNum + 1) + j + 1));
			pPiece->AddBoundary(pGraph->GetBoundary((i + 1)*(m_nColNum + 1) + j + 1,
				(i + 1)*(m_nColNum + 1) + j));
			pPiece->AddBoundary(pGraph->GetBoundary((i + 1)*(m_nColNum + 1) + j, 
				i*(m_nColNum + 1) + j));

			pPiece->ResortBoundaries();
			pGraph->AddPiece(pPiece);
		}
	}

	pGraph->UpdatePointsIds();

	return pGraph;
}
